package android.pot.com.smartcar.ui.partner;

import android.content.Intent;
import android.os.Bundle;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.CommonAdapter;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.ViewHolder;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.entity.MineEntity;
import android.pot.com.smartcar.entity.PartNerEntity;
import android.pot.com.smartcar.fragment.CallDialogView;
import android.pot.com.smartcar.fragment.WithDrawDialogView;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.util.DensityUtils;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by zhaoshilu on 2017/11/27.
 */
public class MyPartNerActivity extends SwipeBackActivity {

    private RefreshLayout refreshLayout;

    private ListView listview;

    private TextView tv_phone,tv_promotion_code,tv_brokerage,tv_cumulative_order,tv_total_price;

    private boolean showLoading = true;

    private int new_order_num = 0;

    private String useableMoney;

    private CommonAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_partner);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();
        addListener();
        initData();
    }

    @Override
    protected void initView() {
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("合作伙伴");
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_promotion_code = (TextView) findViewById(R.id.tv_promotion_code);
        tv_brokerage = (TextView) findViewById(R.id.tv_brokerage);
        tv_cumulative_order = (TextView) findViewById(R.id.tv_cumulative_order);
        tv_total_price = (TextView) findViewById(R.id.tv_total_price);

        initListView();
        initRefreshView();
    }


    @Override
    protected void addListener() {
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToFinishActivity();
            }
        });


    }

    private void initListView(){
        listview = (ListView) findViewById(R.id.lv_list);
        final List<MineEntity> listData = new ArrayList<>();
        MineEntity entity1 = new MineEntity("客户订单",R.mipmap.img_my_order);
        MineEntity entity2 = new MineEntity("客户列表",R.mipmap.img_custom);
        MineEntity entity3 = new MineEntity("提现",R.mipmap.img_withdraw);
        MineEntity entity4 = new MineEntity("提现记录",R.mipmap.img_withdraw_record);

        listData.add(entity1);
        listData.add(entity2);
        listData.add(entity3);
        listData.add(entity4);
        mAdapter = new CommonAdapter<MineEntity>(MyPartNerActivity.this,listData,R.layout.listcell_my_z) {
            @Override
            public void convert(final ViewHolder helper, MineEntity item) {
                helper.setImageResource(R.id.iv_icon,item.getDrawableRes());
                helper.setText(R.id.tv_title,item.getTitle());
                if (item.getTitle().equals("提现记录")){
                    helper.setVisibility(R.id.bottom_line,View.GONE);
                }else{
                    helper.setVisibility(R.id.bottom_line,View.VISIBLE);
                }
                if (item.getTitle().equals("客户订单")){
                    if (new_order_num > 0){
                        helper.setVisibility(R.id.tv_point,View.VISIBLE);
                        if(new_order_num>99){
                            helper.setText(R.id.tv_point,"99+");
                        }else {
                            helper.setText(R.id.tv_point, new_order_num + "");
                        }

                    }else{
                        helper.setVisibility(R.id.tv_point,View.GONE);
                    }
                }
                helper.setOnClickListener(R.id.out_layout, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (listData.get(helper.getPosition()).getTitle()){
                            case "客户订单":
                                startActForResult(MyPartNerActivity.this, PartnerOrderActivity.class);
                                break;
                            case "客户列表":
                                startAct(MyPartNerActivity.this, PartnerCustomListActivity.class);
                                break;
                            case "提现":
                                if (!TextUtils.isEmpty(useableMoney)){
                                    double money = Double.parseDouble(TextCheckUtil.formate2Money(useableMoney));
                                    WithDrawDialogView dialogView = new WithDrawDialogView(MyPartNerActivity.this,money);
                                    dialogView.show(getSupportFragmentManager(),"dialogView");
                                    dialogView.setMethodClickListener(new WithDrawDialogView.OnMethodClickListener() {
                                        @Override
                                        public void methodClick(String num) {

                                            withDraw(Double.parseDouble(num));
                                        }
                                    });
                                }

                                break;
                            case "提现记录":
                                startAct(MyPartNerActivity.this, WithDrawRecordActivity.class);
                                break;
                        }
                    }
                });
            }
        };
        listview.setAdapter(mAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            }
        });
    }

    private void initRefreshView() {
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showLoading = false;
                getDetailData();
            }
        });



    }

    @Override
    protected void initData() {

        getDetailData();
    }

    private void withDraw(double money) {
        Map<String, String> params = new HashMap<>();
        params.put("money",money+"");
        LoadingTool.StartLoading(this);
        Action.get().withdraw(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message, JSONObject response) {
                LoadingTool.EndLoading(MyPartNerActivity.this);
                CallDialogView dialogView = new CallDialogView(MyPartNerActivity.this, "提现已申请，待审核");
                dialogView.show(getSupportFragmentManager(), "dialogView");
                getDetailData();
            }

        });
    }

    public  SpannableString changTVsize(String value) {
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(0.8f), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
    private void getDetailData() {
        Map<String, String> params = new HashMap<>();
        if (showLoading) {
            LoadingTool.StartLoading(this);
        }
        Action.get().distributor(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message, JSONObject response) {
                if (showLoading) {
                    LoadingTool.EndLoading(MyPartNerActivity.this);
                }
                PartNerEntity partNerEntity = GsonUtil.getObject(response.toString(), PartNerEntity.class);
                tv_phone.setText("尊敬的："+partNerEntity.getPhone());
                tv_promotion_code.setText("推广码："+partNerEntity.getPromotion_code());
                useableMoney = partNerEntity.getBrokerage();
//                partNerEntity.setBrokerage("111111101.00");
//                partNerEntity.setTotal_price("111.00");
                DisplayMetrics dm = getResources().getDisplayMetrics();
                float value  = dm.scaledDensity;
                if (TextCheckUtil.formate2Money(partNerEntity.getBrokerage()).length()>8) {
                    int size = DensityUtils.dp2px(18,MyPartNerActivity.this);
                    tv_brokerage.setTextSize(size/value);
                }else{
                    int size = DensityUtils.dp2px(26,MyPartNerActivity.this);
                    tv_brokerage.setTextSize(size/value);
                }
                if (TextCheckUtil.formate2Money(partNerEntity.getTotal_price()).length()>8) {
                    int size = DensityUtils.dp2px(18,MyPartNerActivity.this);
                    tv_total_price.setTextSize(size/value);
                }else{
                    int size = DensityUtils.dp2px(26,MyPartNerActivity.this);
                    tv_total_price.setTextSize(size/value);
                }
                tv_brokerage.setText(changTVsize(TextCheckUtil.formate2Money(partNerEntity.getBrokerage())));
                tv_cumulative_order.setText(TextCheckUtil.CheckString(partNerEntity.getCumulative_order()));
                tv_total_price.setText(changTVsize(TextCheckUtil.formate2Money(partNerEntity.getTotal_price())));
                new_order_num = partNerEntity.getNew_order_num();
                mAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                super.onFailure(statusCode, error_msg);
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2000){
            getDetailData();
        }
    }
}